import {
	defineStore
} from 'pinia';
import {
	useUserStore
} from "@/stores/user.js"
import {
	SERVER_URL
} from "@/config/index.js"

export const useShoppingCartStore = defineStore('shopping-cart', {
	state: () => {
		return {
			products: []
		};
	},
	actions: {
		loadShoppingCart() {
			const userStore = useUserStore()
			uni.request({
				url: SERVER_URL + '/customer/shopping-cart',
				method: "GET",
				header: {
					"content-type": "application/json",
					"authorization": userStore.token
				},
				success: (res) => {
					if (res.statusCode === 200) {
						this.products = res.data
					}
				}
			});
		},
		addProduct(e) {
			const userStore = useUserStore()
			if (this.products.some((item) => {
					return item.flower.id === e.flower_id
				})) {
				uni.showToast({
					title: "已在购物车中"
				})
				return
			}
			uni.request({
				url: SERVER_URL + '/customer/shopping-cart',
				method: "POST",
				data: {
					flower_id: e.flower_id,
					quantity: e.quantity
				},
				header: {
					"content-type": "application/json",
					"authorization": userStore.token
				},
				success: (res) => {
					if (res.statusCode === 200) {
						uni.showToast({
							title: "添加成功"
						})
					}
				},
				complete: () => {
					this.loadShoppingCart()
				}
			});
		},
		deleteProduct(ids) {
			return new Promise((resolve, reject) => {
				const params = '?id=' + ids.join("&id=")
				uni.request({
					url: SERVER_URL + '/customer/shopping-cart' + params,
					method: "DELETE",
					header: {
						"authorization": userStore.token
					},
					success: (res) => {
						if (res.statusCode === 200) {
							resolve()
						} else {
							reject()
						}
					},
					fail: (err) => {
						reject(err)
					},
					complete: () => {
						shoppingCartStore.loadShoppingCart()
					}
				});
			})
		}
	},
	persist: {
		// 调整为兼容多端的API
		storage: {
			setItem(key, value) {
				uni.setStorageSync(key, value)
			},
			getItem(key) {
				return uni.getStorageSync(key)
			},
		},
	}
});